const multer = require('multer');
const path = require('path');
const fs = require('fs');
//fs模块的扩展版
const fsextra = require('fs-extra');


//异步创建路径文件
async function ensureDirExists(dir) {
    try {
        await fs.promises.access(dir);
    } catch {
        await fs.promises.mkdir(dir, { recursive: true });
    }
}

//创建Multer 配置
function createStorageConfig(folderName, options = {}) {
    return multer.diskStorage({
        destination: async (req, file, cb) => {
            try {
                //文件类型
                let fileName = file.fieldname;
                //路径
                let imgPath = folderName[fileName];
                const userId = req.user.userid; // 假设用户信息已通过认证中间件附加到req
                const userDir = path.join('uploads', `user_${userId}`, imgPath);

                // 确保用户目录存在
                await fsextra.ensureDir(userDir);

                cb(null, userDir);
            } catch (err) {
                cb(err);
            }
        },
        filename: (req, file, cb) => {
            const ext = path.extname(file.originalname);
            const name = options.keepOriginalName
                ? path.basename(file.originalname, ext)
                : `${Date.now()}-${Math.round(Math.random() * 1E9)}`;
            cb(null, name + ext);
        }
    });
}

//创建存储文件保存方法，包括保存位置
function createUploader(folderName = {}, options = {}) {
    if (!folderName || typeof folderName !== 'object' || Array.isArray(folderName) || Object.keys(folderName).length === 0) {
        return { message: "图片保存路径必须是非空对象" }
    }
    return multer({
        storage: createStorageConfig(folderName, options),
        fileFilter: (req, file, cb) => {
            if (options.allowedMimeTypes && !options.allowedMimeTypes.includes(file.mimetype)) {
                return cb(new Error(`只支持 ${options.allowedMimeTypes.join(', ')} 格式`));
            }
            cb(null, true);
        },
        limits: options.limits || { fileSize: 10 * 1024 * 1024 }
    });
}


module.exports = { createUploader };